import cv2
from math import *
import numpy as np


def dumpRotateImage(img, degree):
    height, width = img.shape[:2]
    heightNew = int(width * fabs(sin(radians(degree))) + height * fabs(cos(radians(degree))))
    widthNew = int(height * fabs(sin(radians(degree))) + width * fabs(cos(radians(degree))))
    matRotation = cv2.getRotationMatrix2D((width // 2, height // 2), degree, 1)
    # matRotation[0,2] += (widthNew - width)//2
    # matRotation[1,2] += (heightNew - height)//2
    imgRotation = cv2.warpAffine(img, matRotation, (widthNew, heightNew), borderValue=(255, 255, 255))

    matRotation2 = cv2.getRotationMatrix2D((widthNew // 2, heightNew // 2), degree, 1)
    imgRotation2 = cv2.warpAffine(img, matRotation2, (widthNew, heightNew), borderValue=(255, 255, 255))
    return imgRotation, imgRotation2, matRotation


def draw_box(img, box):
    cv2.line(img, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 3)
    cv2.line(img, (box[0], box[1]), (box[4], box[5]), (0, 255, 0), 3)
    cv2.line(img, (box[2], box[3]), (box[6], box[7]), (0, 255, 0), 3)
    cv2.line(img, (box[4], box[5]), (box[6], box[7]), (0, 255, 0), 3)
    return img


def show_img_rotate(img_path, degree):
    """
    img_path:
    degree: 旋转角度
    """

    image = cv2.imread(img_path)
    imgRotation, imgRotation2, matRotation = dumpRotateImage(image, degree)
    box = [200, 250, 250, 200, 230, 280, 280, 230]

    reverseMatRotation = cv2.invertAffineTransform(matRotation)
    pt1 = np.dot(matRotation, np.array([[box[0]], [box[1]], [1]]))
    pt2 = np.dot(matRotation, np.array([[box[2]], [box[3]], [1]]))
    pt3 = np.dot(matRotation, np.array([[box[4]], [box[5]], [1]]))
    pt4 = np.dot(matRotation, np.array([[box[6]], [box[7]], [1]]))
    # Q = np.dot(matRotation, np.array([[P[0]], [P[1]], [1]]))

    # print(pt1, pt2, pt3, pt4)
    box2 = [pt1[0], pt1[1], pt2[0], pt2[1], pt3[0], pt3[1], pt4[0], pt4[1]]

    # cv2.imwrite('./rotate_test.png', draw_box(imgRotation, box2))
    cv2.imwrite('./img.jpg', draw_box(image, box))
    img_after_rorate = draw_box(imgRotation, box2)
    cv2.imwrite('./rotated_img.jpg', img_after_rorate)
    return img_after_rorate, box

def get_rotated_img(img_path, coord_list, degree):
    """返回旋转后的图像以及对应的坐标"""
    pass



if __name__ == '__main__':
    img_after_rorate, coord_list = show_img_rotate('../dataset/SparkAI/train/train_data/001L0/L0000.jpg', 90)
    cv2.imshow("img_after_rotate: ", img_after_rorate)
    print(coord_list)
    cv2.waitKey(0)

